package com.xxx.system.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component//
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("front".equals(request.getHeader("requestType"))) {
            return true;//如果是前台门户的请求头,说明是前台门户的请求,暂时放行
        }

        String token = request.getHeader("token");

        if (StrUtil.isBlank(token)) {
            response.setContentType(ContentType.JSON.toString());//设置内容类型,告诉别人我要返回自定义的json字符串
            response.getWriter().println("{\"success\":false,\"msg\":\"toLogin\"}");//{"success":false,"message":"toLogin"}

            return false;//不放行
        }

        try {
            Payload payload = JwtUtil.parseJwtToken(token);

            //HandlerMethod method = (HandlerMethod) handler;
            //PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
            //if (methodAnnotation != null) {
            //    return false;
            //}
            //String needPerm = methodAnnotation.sn();
            //List<String> ownPerms = payload.getPermissions();
            //if (!ownPerms.contains(needPerm)) {
            //    response.setContentType(ContentType.JSON.toString());//设置内容类型,告诉别人我要返回自定义的json字符串
            //    response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");//{"success":false,"message":"toLogin"}
            //    return false;
            //}
        } catch (Exception e) {
            e.printStackTrace();

            response.setContentType(ContentType.JSON.toString());//设置内容类型,告诉别人我要返回自定义的json字符串
            response.getWriter().println("{\"success\":false,\"msg\":\"toLogin\"}");//{"success":false,"message":"toLogin"}

            return false;//不放行
        }

        return true;//放行
    }
}
